import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { from } from 'rxjs/internal/observable/from';
import { count, map, mapTo, mergeMap, switchMap } from 'rxjs/operators';
import { Project, User, Auth } from '../domain';

@Injectable()
export class UserService {
    private readonly domain = 'users';

    private headers = new HttpHeaders({
        'Content-Type': 'application/json',
    });


    private token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' +
        '.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9' +
        '.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ';

    constructor(
        private http: HttpClient,
        @Inject('BASE_CONFIG') private config
    ) { }


    // POST
    register(user: User): Observable<Auth> {

        user.id = null;

        const uri = `${this.config.uri}/${this.domain}`;

        return this.http.get<User[]>(uri, { params: { email: user.email } }).pipe(
            switchMap(res => {
                if (res.length > 0) {
                    throw 'user existed';
                }

                return this.http.post<User>(uri, JSON.stringify(user), {
                    headers: this.headers,
                }).pipe(
                    map(r => ({
                        token: this.token,
                        user: r
                    }))
                );
            })
        )
    }

    login(username: string, password: string): Observable<Auth> {

        const uri = `${this.config.uri}/${this.domain}`;

        return this.http.get<User[]>(uri, {params: {email: username, password}}).pipe(
            map(res => {
                if (res.length === 0) {
                    throw 'username or password not match'
                }
                return {
                    token: this.token,
                    user: res[0]
                }
            })
        );
    }
}
